package com.hongmeng.teamwork.factory.attachment;

import com.hongmeng.teamwork.entity.dto.AttachmentDto;
import com.hongmeng.teamwork.enums.AttachmentEnum;
import com.hongmeng.teamwork.utils.FeishuUtil;
import com.hongmeng.teamwork.utils.FileUtil;
import com.lark.oapi.Client;
import com.lark.oapi.service.im.v1.enums.CreateImageImageTypeEnum;
import com.lark.oapi.service.im.v1.model.CreateImageReq;
import com.lark.oapi.service.im.v1.model.CreateImageReqBody;
import com.lark.oapi.service.im.v1.model.CreateImageResp;
import lombok.extern.log4j.Log4j2;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.io.File;

@Log4j2
@Component
public class ImgAttachmentHandler implements AttachmentHandler{

    @Resource
    private Client client;

    @Override
    public AttachmentEnum getEnum() {
        return AttachmentEnum.IMAGE;
    }

    @Override
    public String upload(AttachmentDto attachmentDto) throws Exception {
        File file = FileUtil.transferToFile(attachmentDto.getFile());
        CreateImageResp resp = client.im().image()
                .create(CreateImageReq.newBuilder()
                        .createImageReqBody(CreateImageReqBody.newBuilder()
                                .imageType(CreateImageImageTypeEnum.MESSAGE)
                                .image(file)
                                .build())
                        .build(),
                        FeishuUtil.getRequestOptions(getHeader(), attachmentDto.getAccessToken()));
        file.delete();
        return resp.getData().getImageKey();
    }
}
